<template>
	<div class="edit-popup">
		<popup ref="popupRef" :title="popupTitle" :async="true" width="750px" @confirm="handleSubmit"
			@close="handleClose">
			<el-form ref="formRef" :model="formData" label-width="90px" :rules="formRules">
				<el-form-item label="业务名称" prop="name">
					<el-input v-model="formData.name" clearable placeholder="请输入业务名称" />
				</el-form-item>
				<el-form-item label="金额" prop="name">
					<el-input v-model="formData.price" clearable placeholder="请输入金额" />
				</el-form-item>
				<el-form-item label="合同id" prop="contract_id">
					<el-button type="primary" style="margin-left: 16px" @click="drawer = true">
						选择合同模版
					</el-button>
					<div class="form-tips" v-if="formData.contract_id!=''" style="margin-left: 20px;">
						已选择合同模版：{{formData.contract_name}}<br />
					</div>
				</el-form-item>

<!-- 				<el-form-item v-for="(domain, index) in formData.spec_info" :key="domain.key" :label="'规格数据' + index">
					名称：<el-input v-model="domain.name" placeholder="请输入规格名称" style="width: 150px;margin-right: 20px;" />
					金额：<el-input v-model="domain.price" style="width: 70px; margin-right: 20px;" />
					单位：<el-input v-model="domain.unit" style="width: 50px;margin-right: 20px;" />
					<el-button type="danger" @click.prevent="removeDomain(domain)">
						删除
					</el-button>
					<el-form-item style="margin-left: 20px;" v-if="formData.spec_info.length==index+1">
						<el-button @click="addDomain">新增</el-button>
					</el-form-item>
				</el-form-item> -->
				<el-form-item label="合同展示" prop="contract_status">
					<el-radio-group v-model="formData.contract_status">
						<el-radio label="0" size="large">隐藏</el-radio>
						<el-radio label="1" size="large">展示</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="营业执照" prop="business_license">
					<el-radio-group v-model="formData.business_license" placeholder="请选择营业执照">
						<el-radio v-for="(item, index) in dictData.form_rule" :key="index"
							:label="parseInt(item.value)">
							{{ item.name }}
						</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="姓名" prop="full_name">
					<el-radio-group v-model="formData.full_name" placeholder="请选择姓名">
						<el-radio v-for="(item, index) in dictData.form_rule" :key="index"
							:label="parseInt(item.value)">
							{{ item.name }}
						</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="身份证号" prop="id_card">
					<el-radio-group v-model="formData.id_card" placeholder="请选择身份证号">
						<el-radio v-for="(item, index) in dictData.form_rule" :key="index"
							:label="parseInt(item.value)">
							{{ item.name }}
						</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="手机号" prop="mobile">
					<el-radio-group v-model="formData.mobile" placeholder="请选择手机号">
						<el-radio v-for="(item, index) in dictData.form_rule" :key="index"
							:label="parseInt(item.value)">
							{{ item.name }}
						</el-radio>
					</el-radio-group>
				</el-form-item>
<!-- 				<el-form-item label="业务详情页" prop="detail">
					<editor class="flex-1" v-model="formData.detail" :height="500" />
				</el-form-item> -->

			</el-form>
		</popup>
	</div>
	<el-drawer v-model="drawer" title="I am the title" :with-header="false" size="50%" @open="drawerInfo">
		<el-card class="!border-none" shadow="never">
			<div class="mt-4">
				<el-table :data="pager.lists">
					<el-table-column label="模版名称" prop="name" show-overflow-tooltip />
					<el-table-column label="" prop="create_time" show-overflow-tooltip />

					<el-table-column label="操作" width="120" fixed="right">
						<template #default="{ row }">
							<div v-if="row.id==formData.contract_id">
								已选择
							</div>
							<div v-else>
								<el-button type="primary" link @click="checkContract(row)">
									选择
								</el-button>
							</div>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<div class="flex mt-4 justify-end">
				<pagination v-model="pager" @change="getLists" />
			</div>
		</el-card>
	</el-drawer>
</template>

<script lang="ts" setup name="businessInfoEdit">
	import type { FormInstance } from 'element-plus'
	import Popup from '@/components/popup/index.vue'
	import { usePaging } from '@/hooks/usePaging'
	import { apiBusinessInfoAdd, apiBusinessInfoEdit, apiBusinessInfoDetail, apiCheckContract } from '@/api/business_info'
	import { apiContractTemplateLists } from '@/api/contract_template'
	import type { PropType } from 'vue'
	import { reactive, ref } from 'vue'

	const queryParams = reactive({
		name: '',
	})


	// 分页数据
	const pager = reactive({
		page: 1,
		size: 15,
		count: 0,
		lists: [] as any[],
		extend: {} as Record<string, any>
	})

	const getLists = async () => {
		await apiContractTemplateLists({
			page_no: pager.page,
			page_size: pager.size,
		}).then((res : any) => {
			pager.count = res?.count
			pager.lists = res?.lists
			pager.extend = res?.extend
		})
	}

	const drawerInfo = async () => {
		getLists()

	}

	const checkContract = async (row : any) => {
		if (mode.value == 'edit') {
			await apiCheckContract({
				id: formData.id,
				contract_id: row.id,
			})
			const data = await apiBusinessInfoDetail({
				id: formData.id
			})
			setFormData(data)
			emit('success')
		}
		formData.contract_id = row.id
		formData.contract_name = row.name

	}


	const drawer = ref(false)
	const emit = defineEmits(['success', 'close'])
	const formRef = shallowRef<FormInstance>()
	const popupRef = shallowRef<InstanceType<typeof Popup>>()
	const mode = ref('add')
	const dynamicValidateForm = reactive<{
		domains : DomainItem[]
		price : string
	}>({
		domains: [
			{
				key: 1,
				name: '',
				price: '',
				unit: ''
			},
		],
		price: '',
	})
	interface DomainItem {
		key : number
		name : string
		price : string
		unit : string
	}



	// 弹窗标题
	const popupTitle = computed(() => {
		return mode.value == 'edit' ? '编辑业务表' : '新增业务表'
	})

	// 表单数据
	const formData = reactive({
		id: '',
		name: '',
		contract_id: '',
		business_license: 2,
		full_name: 2,
		id_card: 2,
		mobile: 2,
		detail: '',
		contract_name: '',
		spec_info: [
			{
				key: Date.now(),
				name: '',
				price: '',
				unit: ''
			},
		],
		price:'',
		contract_status:0

	})



	// 表单验证
	const formRules = reactive<any>({

	})


	// 获取详情
	const setFormData = async (data : Record<any, any>) => {
		for (const key in formData) {
			if (data[key] != null && data[key] != undefined) {
				//@ts-ignore
				formData[key] = data[key]
			}
		}


	}

	const getDetail = async (row : Record<string, any>) => {
		const data = await apiBusinessInfoDetail({
			id: row.id
		})
		setFormData(data)
	}


	// 提交按钮
	const handleSubmit = async () => {
		await formRef.value?.validate()
		const data = { ...formData, }
		mode.value == 'edit'
			? await apiBusinessInfoEdit(data)
			: await apiBusinessInfoAdd(data)
		popupRef.value?.close()
		emit('success')
	}

	//打开弹窗
	const open = (type = 'add') => {
		mode.value = type
		popupRef.value?.open()
	}

	// 关闭回调
	const handleClose = () => {
		emit('close')
	}

	const removeDomain = (item : DomainItem) => {
		const index = formData.spec_info.indexOf(item)
		if (index !== -1) {
			formData.spec_info.splice(index, 1)
		}
	}

	const addDomain = () => {
		formData.spec_info.push({
			key: Date.now(),
			price: '',
			unit: '',
		})
		console.log(formData.spec_info)
	}

	const submitForm = (formEl : FormInstance | undefined) => {
		if (!formEl) return
		formEl.validate((valid) => {
			if (valid) {
				console.log('submit!')
			} else {
				console.log('error submit!')
			}
		})
	}

	const resetForm = (formEl : FormInstance | undefined) => {
		if (!formEl) return
		formEl.resetFields()
	}




	defineProps({
		dictData: {
			type: Object as PropType<Record<string, any[]>>,
			default: () => ({})
		}
	})



	defineExpose({
		open,
		setFormData,
		getDetail
	})
</script>